package com.xian.im.web.common;

import com.xian.im.common.utils.ResponseUtil;
import com.xian.im.modules.mis.BlackProcess;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: xian-code
 * @description: 黑名单拦截器
 * @author: liru.xian
 * @create: 2021-01-20 01:58
 **/
@Component
public class BlackInterceptor implements HandlerInterceptor {

    @Autowired
    private BlackProcess blackProcess;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ip = request.getHeader("X-Real-IP");
        ip  = StringUtils.isNotBlank(ip)? ip : "127.0.0.1";
        boolean b = blackProcess.dealRequest(ip);
        if(b){
            ResponseUtil.renderJson(response, "请求错误，请联系管理员", 1015);
            return Boolean.FALSE;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
